#include <iostream>
#include <string>
#include <errno.h>
#include <netinet/in.h>
#include <unistd.h>
// inet_pton函数所需头文件
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>

using namespace std;

// 第三个参数指定长度，如果发送不完可以接着发送，知道发送完指定长度
int MySend(int iSock, char *pchBuf, size_t tLen)
{
    int iThisSend;
    unsigned int iSended = 0;
    if (tLen == 0)
    {
        return 0;
    }
    while (iSended < tLen)
    {
        do
        {
            iThisSend = send(iSock, pchBuf, tLen - iSended, 0);
        } while ((iThisSend < 0) && (errno == EINTR));
        if (iThisSend < 0)
        {
            return iSended;
        }
        iSended += iThisSend;
        pchBuf += iThisSend;
    }
    return tLen;
}

#define DEFAULT_PORT 6666

int main(int argc, char *argv[])
{
    int connfd = 0;
    int cLen = 0;
    struct sockaddr_in client;
    if (argc < 2)
    {
        cout << " Uasge: clientent [server IP address]" << endl;
        return -1;
    }
    client.sin_family = AF_INET;
    client.sin_port = htons(DEFAULT_PORT);
    client.sin_addr.s_addr = inet_addr(argv[1]);
    connfd = socket(AF_INET, SOCK_STREAM, 0);
    if (connfd < 0)
    {
        cout << "socket() failure!" << endl;
        return -1;
    }
    if (connect(connfd, (struct sockaddr *)&client, sizeof(client)) < 0)
    {
        cout << "connect() failure!" << endl;
        return -1;
    }
    // 往服务器发送0123456789的字符串
    // 因为双方不知道字符串多长，所以发送的数据前4个字节表示字符串的大小
    ssize_t writeLen;
    char *sendMsg = "0123456789";
    // string sendMsg = "0123456789";
    int tLen = strlen(sendMsg);
    // int tLen = sendMsg.size();
    cout << "tLen: " << tLen << endl;
    int iLen = 0;
    char *pBuff = new char[100];
    *(int *)(pBuff + iLen) = htonl(tLen);
    iLen += sizeof(int);
    memcpy(pBuff + iLen, sendMsg, tLen);
    iLen += tLen;
    writeLen = MySend(connfd, pBuff, iLen);
    if (writeLen < 0)
    {
        cout << "write failure" << endl;
        close(connfd);
        return 0;
    }
    else
    {
        cout << "write sucess, writelen: " << writeLen << ", sendMsg: " << sendMsg << endl;
    }
    close(connfd);
    return 0;
}
